//
//  PPTimelinePictureViewController.m
//  pickpic
//
//  Created by Jinxiao on 10/4/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPTimelinePictureViewController.h"
#import "PPCommentTimelineViewController.h"
#import "PPTimelineLikesViewController.h"
#import "PPTimelinePictureFlowViewController.h"
#import "PPComplainViewController.h"

#import "PPTimelinePictureDescriptionView.h"
#import "PPTimelinePictureStatusView.h"

#import "PPAlbumShareActionView.h"
#import "PPTimelinePictureActionView.h"

#import "PPSocializationManager.h"

@interface PPTimelinePictureViewController () <PPImageFlowViewControllerDelegate, PPCommentTimelineViewControllerDelegate>
@property (readwrite, nonatomic, strong) PPTimelinePictureStatusView *statusView;
@property (readwrite, nonatomic, strong) PPTimelinePictureDescriptionView *descriptionView;
@end

@implementation PPTimelinePictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-nav-grid-yellow"] style:UIBarButtonItemStylePlain target:self action:@selector(switchItemDidPressed)];

    _statusView = [[NSBundle mainBundle] loadNibNamed:@"PPTimelinePictureStatusView" owner:nil options:nil].firstObject;
    [_statusView.commentButton addTarget:self action:@selector(commentButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [_statusView.commentCountButton addTarget:self action:@selector(commentButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [_statusView.likeCountButton addTarget:self action:@selector(likeCountButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [_statusView.likeCountButton2 addTarget:self action:@selector(likeCountButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_statusView];

    _descriptionView = [[PPTimelinePictureDescriptionView alloc] init];
    [self.view addSubview:_descriptionView];

    [_statusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.height.equalTo(@(39));
    }];

    [_descriptionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.bottom.equalTo(_statusView.mas_top);
    }];

    [self updateRelevantInfos];
}

- (void)setPictures:(NSArray<PPTimelinePictureObject *> *)pictures {
    _pictures = pictures;

    NSMutableArray <PPAbstractArtwork *> *artworks = [NSMutableArray array];
    [pictures enumerateObjectsUsingBlock:^(PPTimelinePictureObject *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
        artwork.URLString = obj.URLString;
        [artworks addObject:artwork];
    }];

    self.artworks = artworks;
}

- (void)updateRelevantInfos {
    if(_albumTitle.length > 0) {
        NSMutableAttributedString *title = [[NSMutableAttributedString alloc] init];

        NSAttributedString *albumTitle = [[NSAttributedString alloc] initWithString:_albumTitle attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:15], NSForegroundColorAttributeName : [UIColor whiteColor]}];
        [title appendAttributedString:albumTitle];

        NSAttributedString *linebreak = [[NSAttributedString alloc] initWithString:@"\r\n"];
        [title appendAttributedString:linebreak];

        NSAttributedString *indexTitle = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%li/%li", self.index + 1, _pictures.count] attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14], NSForegroundColorAttributeName : [UIColor whiteColor]}];
        [title appendAttributedString:indexTitle];

        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.numberOfLines = 0;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.attributedText = title;
        [titleLabel sizeToFit];

        self.navigationItem.titleView = titleLabel;
    }

    PPTimelinePictureObject *picture = [_pictures safeObjectAtIndex:self.index];

    _statusView.picture = picture;

    _descriptionView.desc = picture.desc;
}

- (void)likeCountButtonDidPressed {
    PPTimelineLikesViewController *likeViewController = [[PPTimelineLikesViewController alloc] init];
    likeViewController.type = @2;
    PPTimelinePictureObject *picture = [_pictures safeObjectAtIndex:self.index];
    likeViewController.ID = picture.imageID;
    [self.navigationController pushViewController:likeViewController animated:YES];
}

- (void)commentButtonDidPressed {
    [MobClick event:@"160"];
    PPTimelinePictureObject *picture = [_pictures safeObjectAtIndex:self.index];

    PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
    commentViewController.delegate = self;
    commentViewController.imageID = picture.imageID.integerValue;
    commentViewController.ownerID = _ownerID;
    [self.navigationController pushViewController:commentViewController animated:YES];
}

- (void)switchItemDidPressed {
    [MobClick event:@"156"];
    NSMutableArray *items = [NSMutableArray array];

    [self.artworks enumerateObjectsUsingBlock:^(PPAbstractArtwork *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPImageFlowItem *item = [[PPImageFlowItem alloc] init];
        item.URLString = obj.URLString;
        item.image = obj.image;
        item.representedObject = obj;
        [items addObject:item];
    }];

    PPTimelinePictureFlowViewController *flowViewController = [[PPTimelinePictureFlowViewController alloc] init];
    flowViewController.items = items;
    flowViewController.delegate = self;
    flowViewController.albumTitle = _albumTitle;
    [self.navigationController pushViewController:flowViewController animated:NO];
}

- (void)didEndScrolling {
    [super didEndScrolling];

    [self updateRelevantInfos];
}

- (BOOL)scrollsOnScrolling {
    return YES;
}


- (void)pictureViewCell:(PPAbstractPictureViewCell *)pictureViewCell didRecognizedLongPressGesture:(UILongPressGestureRecognizer *)gesture {

    [MobClick event:@"161"];
    UIView *displayView = self.navigationController.view;

    PPTimelinePictureActionView *actionView = [[NSBundle mainBundle] loadNibNamed:@"PPTimelinePictureActionView" owner:nil options:nil].firstObject;

    actionView.frame = CGRectMake(0, displayView.height - actionView.height, displayView.width, actionView.height);

    DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:displayView contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

    __weak typeof(self)weakSelf = self;
    __weak typeof(popoverView)weakPopover = popoverView;

    [actionView.cancelButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:nil];
    } forControlEvents:UIControlEventTouchUpInside];

    [actionView.reportButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:^{
            [MobClick event:@"162"];
            [weakSelf displayNavigationBarAnimated:YES completion:^{

                PPTimelinePictureObject *picture = [weakSelf.pictures safeObjectAtIndex:weakSelf.index];

                PPComplainViewController *vc = [[UIStoryboard storyboardWithName:@"Setting" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"PPComplainViewController"];
                vc.type = @2;
                vc.relationID = picture.imageID;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }];

        }];
    } forControlEvents:UIControlEventTouchUpInside];

    [popoverView displayAnimated:YES completion:nil];
}

- (void)displayNavigationBarAnimated:(BOOL)animated completion:(void (^)(void))completion {
    [_statusView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.height.equalTo(@(39));
        make.bottom.equalTo(self.view.mas_bottom);
    }];

    [self.view updateConstraintsIfNeeded];

    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        !completion ? : completion();
    }];
}

- (void)dismissNavigationBarAnimated:(BOOL)animated completion:(void (^)(void))completion {
    [_statusView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.height.equalTo(@(39));
        make.top.equalTo(self.view.mas_bottom);
    }];

    [self.view updateConstraintsIfNeeded];

    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        !completion ? : completion();
    }];
}

#pragma mark - PPImageFlowViewControllerDelegate

- (void)flowViewController:(PPImageFlowViewController *)flowViewController didSelectFlowItem:(PPImageFlowItem *)flowItem atIndex:(NSInteger)index {
    [self scrollIndexToVisible:index animated:NO];

    [self updateRelevantInfos];

    [self.navigationController popToViewController:self animated:NO];
}

#pragma mark - PPCommentTimelineViewControllerDelegate
- (void)commentTimelineViewController:(PPCommentTimelineViewController *)commentTimelineViewController didInsertComment:(PPTimelineCommentObject *)comment {
    PPTimelinePictureObject *picture = [_pictures safeObjectAtIndex:self.index];
    picture.commentCount++;
    _statusView.picture = picture;
}

- (void)commentTimelineViewController:(PPCommentTimelineViewController *)commentTimelineViewController didRemoveComment:(PPTimelineCommentObject *)comment {
    PPTimelinePictureObject *picture = [_pictures safeObjectAtIndex:self.index];
    picture.commentCount--;
    _statusView.picture = picture;
}

@end
